package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.merchanth5.dao.CSDao;
import cc.linker.steplink.crm.merchanth5.dao.CourseDao;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 客服
 * @Author: wuhangfeng
 * @Date: Created in 2020/2/25 14:39
 * @Version: 1.0.20
 */
@Service
public class CSService {

    @Value("${system.scrm.getwxlist}")
    private String accountUrl;

    @Value("${idp.service.url}")
    private String idpUrl;
    @Value("${casclient.clientHost}")
    private String clientHost;

    @Autowired
    private HttpService httpService;

    @Autowired
    private MerchantSalerService merchantSalerService;

    @Autowired
    private CSDao csDao;

    public String getEntrance(String belongId, String goodsId, String goodsImg, WxUser wxUser,Integer source) throws IOException, URISyntaxException {
        Map<String, Object> pushData = new HashMap<>();
        String orgId = wxUser.getOrgId();
        Map<String,String> salerInfo = null;
        String result = "";
        if(StringUtils.isNotEmpty(belongId)){
            salerInfo = csDao.getSalerAdminId(belongId);
            if(salerInfo!=null){
                //联盟商家客服
                pushData.put("uid",salerInfo.get("adminId"));
                result = httpService.doGet(accountUrl + "?action=getbCustomerInfo", pushData);
            }else{
                //机构客服
                pushData.put("orgcode", orgId);
                pushData.put("isagent", 0);
                result = httpService.doGet(accountUrl + "?action=getOrgCustomerInfo", pushData);
            }
        }else{
            //机构客服
            pushData.put("orgcode", orgId);
            pushData.put("isagent", 0);
            result = httpService.doGet(accountUrl + "?action=getOrgCustomerInfo", pushData);
        }
        JSONObject resultMap = JSONObject.parseObject(result);
        if(resultMap.getInteger("RetCode")== 0){
            JSONArray customerList = resultMap.getJSONArray("List");
            if(customerList!=null&&customerList.size()>0){
                List<String> customerAccount = new ArrayList<>();
                for (Object cutomerObj:customerList.toArray()) {
                    JSONObject cutomerInfo = JSONObject.parseObject(cutomerObj.toString());
                    customerAccount.add(cutomerInfo.getString("CustomerAccount"));
                }
                JSONArray adminList = resultMap.getJSONArray("OrgAdminList");
                if(salerInfo!=null){
                    pushData.put("userCode",salerInfo.get("shopId"));
                    pushData.put("shopId",salerInfo.get("shopId"));
                }else{
                    if(adminList.size()>0){
                        JSONObject adminInfo = adminList.getJSONObject(0);
                        pushData.put("userCode",adminInfo.getString("UserCode"));
                        pushData.put("shopId",null);
                    }
                }
                pushData.put("customerAccount",StringUtils.join(customerAccount, ","));
                String extranceUrl = httpService.doGet( idpUrl+"/api/visit/robot/url", pushData);
                JSONObject idpRet = JSONObject.parseObject(extranceUrl);
                if(idpRet.getInteger("rt")==1){
                    Map<String, String> customerBaseInfo = merchantSalerService.getCustomerBaseInfo(wxUser.getCustomerId());
                    JSONArray extrances = idpRet.getJSONArray("data");
                    JSONObject extrance = extrances.getJSONObject(0);
                    String url = extrance.getString("stepCustomerUrl");
                    url = url +"&nickName="+customerBaseInfo.get("customerName")+"&openId="+wxUser.getOpenid()+"&avatar="+customerBaseInfo.get("customerAvatar");
                    if(goodsId!=null){
                        String productId = clientHost+"/h5/mbl/getGoods?goodsId="+goodsId+"&source=idp";
                        url = url +"&imgUrl="+goodsImg+"&productId="+ URLEncoder.encode(productId,"UTF-8");
                        if(source==1){
                            url = url + "&goodsShow=1";
                        }
                    }
                    return url;
                }else{
                    throw GlobalException.build(idpRet.getString("des"));
                }
            }else{
                throw GlobalException.build("该商家尚未开通客服~");
            }
        }else{
            throw GlobalException.build("系统繁忙，请稍后再试~");
        }
    }

    public Object getSessionList(Integer pageIndex, Integer pageSize, String startTime, String endTime,
                                                    Integer keyWordType, String keyWord,String salerId, String orgId) throws IOException, URISyntaxException {
        Map<String,Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(startTime)){
            params.put("startTime",startTime+" 00:00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            params.put("endTime",endTime+" 23:59:59");
        }
        params.put("keyWordType",keyWordType);
        params.put("keyWord",keyWord);
        params.put("salerId",salerId);
        Map<String, Object> pushData = new HashMap<>();
        Map<String,String> salerInfo = new HashMap();
        salerInfo = csDao.getSalerAdminId(salerId);
        //联盟商家客服
        pushData.put("uid", salerInfo.get("adminId"));
        String result = httpService.doGet(accountUrl + "?action=getbCustomerInfo", pushData);
        JSONObject resultMap = JSONObject.parseObject(result);
        if(resultMap.getInteger("RetCode")== 0){
            JSONArray customerList = resultMap.getJSONArray("List");
            List<String> customerAccount = new ArrayList<>();
            if(customerList!=null){
                for (Object cutomerObj:customerList.toArray()) {
                    JSONObject cutomerInfo = JSONObject.parseObject(cutomerObj.toString());
                    customerAccount.add(cutomerInfo.getString("CustomerAccount"));
                }
                params.put("customerAccounts",customerAccount);
                PageHelper.startPage(pageIndex, pageSize);
                return new PageInfo<>(csDao.getSessionList(params));
            }else {
                PageHelper.startPage(pageIndex, pageSize);
                return new PageInfo<>();
            }
        }else{
            throw GlobalException.build("获取会话列表失败");
        }
    }

    public List<Map<String, Object>> getSessionDetail(String sessionId, String orgId) {
        return csDao.getSessionDetail(sessionId);
    }

    public void delSession(Map<String, Object> param) {
        csDao.delSession(param);
    }

    public void setCustomer() throws Exception{
        List<String> salerList = csDao.getSalerAdminIdList();
        for (String uid:salerList) {
            Map<String, Object> pushData = new HashMap<>();
            //联盟商家客服
            pushData.put("uid",uid);
            httpService.doGet(accountUrl + "?action=getbCustomerInfo", pushData);
        }
    }
}
